<?php

namespace App\Services\MiniprogramToGame\HotSearch;

use App\Services\ServiceBase;
use App\Structs\HotSearchStruct;
use Illuminate\Support\Facades\Http;

class Douyin extends ServiceBase
{
    /**
     * 此接口需要事前使用浏览器访问 https://www.douyin.com/hot
     * 获取到cookie，拿到 passport_csrf_token 的信息
     *
     * @return void
     */
    public function reptile()
    {
        $cookie = 'passport_csrf_token=bbee852edb644b757e06a6f8b4244194';
        $url = 'https://www.douyin.com/aweme/v1/web/hot/search/list/?device_platform=webapp&aid=6383&channel=channel_pc_web&detail_list=1&source=6&pc_client_type=1&version_code=170400&version_name=17.4.0&cookie_enabled=true&screen_width=1920&screen_height=1080&browser_language=zh-CN&browser_platform=Win32&browser_name=Chrome&browser_version=118.0.0.0&browser_online=true&engine_name=Blink&engine_version=118.0.0.0&os_name=Windows&os_version=10&cpu_core_num=12&device_memory=8&platform=PC';
        $response = Http::withHeaders([
            'Cookie' => $cookie,
        ])->get($url);
        if (!$response->ok()) {
            return false;
        }

        $data = json_decode($response->body(), true);

        $list = [];
        foreach ($data['data']['word_list'] as $index => $item) {
            $class        = new HotSearchStruct;
            $class->title = $item['word'];
            $class->url   = 'https://www.douyin.com/search/'.urlencode($item['word']);
            if (!isset($item['position'])) {
                $class->isTop = 1;
            } else {
                $class->hotIndex = $item['position'];
                $class->hotValue = $item['hot_value'];
                $class->img      = $item['word_cover']['url_list'][0] ?? '';
            }

            $list[] = $class;
        }

        return $list;
    }

    // 本接口可直接拉取到热搜内容，但没有顶置条目数据
    public function reptileByOffline()
    {
        $url = 'https://www.iesdouyin.com/web/api/v2/hotsearch/billboard/word/';
        $response = Http::get($url);
        if (!$response->ok()) {
            return false;
        }

        $data = json_decode($response->body(), true);

        $list = [];
        foreach ($data['word_list'] as $index => $item) {
            $class           = new HotSearchStruct;
            $class->title    = $item['word'];
            $class->hotIndex = $index+1;
            $class->hotValue = $item['hot_value'];
            $class->url      = 'https://www.douyin.com/search/'.urlencode($item['word']);
            $list[] = $class;
        }

        return $list;
    }
}
